package com.carpedil.smvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/** @author Administrator */
@Controller
public class FileUploadController {
  @RequestMapping("/upload")
  public String upload(
      String filename, @RequestParam("file") MultipartFile file, HttpServletRequest request)
      throws IOException {
    // 获取上传文件名
    String originalFilename = file.getOriginalFilename();
    System.out.println("filename = " + filename);
    // 获取上传文件后缀
    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    // 获取文件上传地址路径

    String filePath = request.getServletContext().getRealPath("/files");
    // 生成随机UID(防止文件重名覆盖问题)
    String uid = UUID.randomUUID().toString();
    // 使用随机UID生成新的文件路径名
    String newFilePathName = filePath + "/" + uid + suffix;
    // 将上传文件保存到新的路径
    try {
      //      FileUtils.copyInputStreamToFile(file.getInputStream(), new File(newFilePathName));
      //      target/day06-SpringMvcDemo2-RBAC/files/a89ae755-1792-4458-8626-4a987c6ec32a.png
      file.transferTo(new File(newFilePathName));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "redirect:/do.jsp";
  }
}
